using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QLHXNK.BusinessLogic;

namespace QLHXNK.Forms
{
    public partial class NewFrmDanhMucChiPhi : Form
    {
        int action = -1;
        private  Expenses expenses;
        private Expenses[] arrExpensesExist = new Expenses[100];
        private Expenses[] arrExpensesDeleted = new Expenses[100];
        DataTable dtExpensesExist;
        private int ExpensesExistCount = 0;
        private int ExpensesDeletedCount = 0;
        private bool isDeleteRow = false;

        private int existRow = -1;
        public NewFrmDanhMucChiPhi()
        {
            InitializeComponent();
            this.CenterToScreen();
        }

        private void NewFrmDanhMucChiPhi_Load(object sender, EventArgs e)
        {
            dtExpensesExist = Expenses.ListExpenses();
            dgvDanhMucChiPhi.DataSource = dtExpensesExist;
            for (int i = 0; i < dtExpensesExist.Rows.Count; i++)
            {
                arrExpensesExist[ExpensesExistCount] = new Expenses(Int32.Parse(dtExpensesExist.Rows[i]["ID"].ToString()),
                                                    dtExpensesExist.Rows[i]["expenses_code"].ToString(),
                                                    dtExpensesExist.Rows[i]["expenses_name"].ToString(),
                                                    dtExpensesExist.Rows[i]["remark"].ToString());
                ExpensesExistCount++;
            }
        }

        
        private void dgvDanhMucChiPhi_KeyDown(object sender, KeyEventArgs e)
        {
            lbKetQua.Visible = false;
            if (e.KeyValue == 46 && ExpensesDeletedCount != 0)
            {
                dgvDanhMucChiPhi.AllowUserToDeleteRows = true;
                DialogResult result = DialogResult;
                if (ExpensesDeletedCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá chi phí này", "Xoá", MessageBoxButtons.YesNo);
                if (ExpensesDeletedCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách chi phí bạn chọn", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    isDeleteRow = true;
                    String note = "";
                    for (int i = 0; i < ExpensesDeletedCount; i++)
                    {
                        if (Expenses.GetExpensesInMonthlyExpenses(arrExpensesDeleted[i].ID).Rows.Count == 0)
                        {
                            int kq = arrExpensesDeleted[i].DeleteExpenses();
                            if (kq == 1)
                                DeleteArrExpensesExist(arrExpensesDeleted[i].ID);
                        }
                        else
                            note = note + "--" + arrExpensesDeleted[i].Name;
                    }
                    ExpensesDeletedCount = 0;
                    if (note != "")
                        MessageBox.Show("Không thể xoá chi phí:" + note);
                }
                else
                    dgvDanhMucChiPhi.AllowUserToDeleteRows = false;
            }
            if (e.KeyValue == 27)
                this.Close();
        }
        private void dgvDanhMucChiPhi_SelectionChanged(object sender, EventArgs e)
        {
            if (existRow != -1)
            {
                dgvDanhMucChiPhi.Rows[existRow].Cells["MaChiPhi"].Value = null;
                dgvDanhMucChiPhi.Rows[existRow].Cells["TenChiPhi"].Value = null;
                dgvDanhMucChiPhi.Rows[existRow].Cells["GhiChu"].Value = null;
                existRow = -1;
            }
            DataGridViewSelectedRowCollection rows = dgvDanhMucChiPhi.SelectedRows;
            if (rows.Count > 0)
            {
                

                ExpensesDeletedCount = 0;
                for (int i = 0; i < rows.Count; i++)
                {
                    DataGridViewRow row = rows[i];
                    
                    if (row.Cells["ID"].Value != null && row.Cells["ID"].Value.ToString() != "")
                    {
                        arrExpensesDeleted[ExpensesDeletedCount++] = new Expenses(Int32.Parse(row.Cells["ID"].Value.ToString()),
                                        row.Cells["MaChiPhi"].Value.ToString(),
                                        row.Cells["TenChiPhi"].Value.ToString(),
                                        row.Cells["GhiChu"].Value.ToString());
                    }
                }
            }
        }

        private void dgvDanhMucChiPhi_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            lbKetQua.Visible = false;
            String expensesCode = "";
            String expensesName = "";
            String remark = "";
            if (dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value != null)
                expensesCode = dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value.ToString().Trim();
            if (dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["TenChiPhi"].Value != null)
                expensesName = dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["TenChiPhi"].Value.ToString().Trim();
            if (dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["GhiChu"].Value != null)
                remark = dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["GhiChu"].Value.ToString().Trim();

            if (e.RowIndex != -1 && action == 0)
            {
                if (expensesCode != "" && expensesName != "")
                {
                    DataTable dtExpenses = Expenses.GetExpensesByCode(expensesCode);
                    if (dtExpenses.Rows.Count > 0)
                    {
                        MessageBox.Show("Đã có chi phí với mã này");
                        existRow = e.RowIndex;
                        action = -1;
                        return;
                    }
                    expenses = Expenses.CreateExspences(expensesCode, expensesName, remark);

                    if (expenses == null)
                        MessageBox.Show("Dữ liệu nhập vào không hơp hợp lệ ");
                    else
                    {
                        ShowNote("Thêm thành công chi phí Mã-"+expenses.Code+"",Color.Blue);
                        arrExpensesExist[ExpensesExistCount++] = expenses;
                    }
                    action = -1;
                }
                else
                {
                    MessageBox.Show("Hảy nhập đầy đủ thông tin cho Chi Phí");
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value = "";
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["TenChiPhi"].Value = "";
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["GhiChu"].Value = "";
                    action = -1;
                    return;
                }
            }
            if (e.RowIndex != -1 && action == 2)
            {
                int i;
                for (i = 0; i < ExpensesExistCount; i++)
                {
                    if (arrExpensesExist[i].ID.ToString() == dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["ID"].Value.ToString())
                        break;
                }
                if (expensesCode != "" && expensesName != "")
                {
                    for (int j = 0; j < dgvDanhMucChiPhi.Rows.Count; j++)
                        if (j != e.RowIndex && dgvDanhMucChiPhi.Rows[j].Cells["MaChiPhi"].Value != null && expensesCode == dgvDanhMucChiPhi.Rows[j].Cells["MaChiPhi"].Value.ToString())
                        {
                            MessageBox.Show("Đã có chi phí với mã này");
                            dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value = arrExpensesExist[i].Code;
                            dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["TenChiPhi"].Value = arrExpensesExist[i].Name;
                            dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["GhiChu"].Value = arrExpensesExist[i].Remark;
                            action = -1;
                            return;
                        }

                    try
                    {
                        int kq= arrExpensesExist[i].UpdateExpenses(expensesCode, expensesName, remark);
                        if (kq == 1)
                            ShowNote("Đã cập nhật thông tin cho chi phí",Color.Blue);
                        action = -1;
                    }
                    catch { action = -1; }
                }
                else
                {
                    MessageBox.Show("Chưa cập nhật thông tin vì không đủ thông tin cho chi phí");
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value = arrExpensesExist[i].Code;
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["TenChiPhi"].Value = arrExpensesExist[i].Name;
                    dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["GhiChu"].Value = arrExpensesExist[i].Remark;
                    action = -1;
                }
            }
        }
        private void dgvDanhMucChiPhi_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (isDeleteRow == true)
            {
                isDeleteRow = false;
                dgvDanhMucChiPhi.DataSource = Expenses.ListExpenses();
            }
        }


        private void dgvDanhMucChiPhi_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            lbKetQua.Visible = false;
            if (e.RowIndex != -1)
            {
                if (dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["ID"].Value.ToString() != "")
                    action = 2;
                else
                    action = 0;
            }
        }


        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnXoa_Click(object sender, EventArgs e)
        {
            lbKetQua.Visible = false;
            if (ExpensesDeletedCount != 0)
            {

                DialogResult result = DialogResult;
                if (ExpensesDeletedCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá chi phí này", "Xoá", MessageBoxButtons.YesNo);
                if (ExpensesDeletedCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách chi phí bạn chọn", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    isDeleteRow = true;
                    String note = "";
                    for (int i = 0; i < ExpensesDeletedCount; i++)
                    {
                        if (Expenses.GetExpensesInMonthlyExpenses(arrExpensesDeleted[i].ID).Rows.Count == 0)
                        {
                            int kq = arrExpensesDeleted[i].DeleteExpenses();
                            if (kq == 1)
                                DeleteArrExpensesExist(arrExpensesDeleted[i].ID);
                        }
                        else
                            note = note + "--" + arrExpensesDeleted[i].Name;
                    }
                    ExpensesDeletedCount = 0;
                    if (note!="")
                        MessageBox.Show("Không thể xoá những chi phí:" + note);
                    dgvDanhMucChiPhi.DataSource = Expenses.ListExpenses();
                }
            }
                   
        }

        private void DeleteArrExpensesExist(int ID)
        {
            int i;
            for (i = 0; i < ExpensesExistCount; i++)
            {
                if (ID == arrExpensesExist[i].ID)
                {
                    ExpensesExistCount--;
                    break;
                }
            }
            for (int j = i; j < ExpensesExistCount; j++)
                arrExpensesExist[j] = arrExpensesExist[j + 1];

        }

        private void UpdateIDInRowByCode(Object expensesCode)
        {
            if (expensesCode == null)
                expensesCode = "";
            for (int i = 0; i < dgvDanhMucChiPhi.Rows.Count; i++)
            {
                if (dgvDanhMucChiPhi.Rows[i].Cells["MaChiPhi"].Value != null && dgvDanhMucChiPhi.Rows[i].Cells["MaChiPhi"].Value.ToString() != "")
                    if (dgvDanhMucChiPhi.Rows[i].Cells["MaChiPhi"].Value.ToString() == expensesCode.ToString())
                        if (dgvDanhMucChiPhi.Rows[i].Cells["ID"].Value == null || dgvDanhMucChiPhi.Rows[i].Cells["ID"].Value.ToString() == "")
                        {
                            DataTable dttmp = Expenses.GetExpensesByCode(dgvDanhMucChiPhi.Rows[i].Cells["MaChiPhi"].Value.ToString());
                            if (dttmp.Rows.Count > 0)
                                dgvDanhMucChiPhi.Rows[i].Cells["ID"].Value = dttmp.Rows[0]["ID"].ToString();
                            break;
                        }
            }
        }

        private void ShowNote(string note, Color foreColor)
        {
            lbKetQua.Visible = true;
            lbKetQua.ForeColor = foreColor;
            lbKetQua.Text = note;
        }

        private void dgvDanhMucChiPhi_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            UpdateIDInRowByCode(dgvDanhMucChiPhi.Rows[e.RowIndex].Cells["MaChiPhi"].Value);
        }

    }
}